package com.gameplatform.service;

import com.gameplatform.exception.BusinessException;
import com.gameplatform.common.enums.ResultCodeEnum;
import com.gameplatform.dto.LoginDTO;
import com.gameplatform.dto.RegisterDTO;
import com.gameplatform.entity.User;
import com.gameplatform.repository.UserRepository;
import com.gameplatform.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    public User register(RegisterDTO registerDTO) {
        if (userRepository.existsByUsername(registerDTO.getUsername())) {
            throw new BusinessException(ResultCodeEnum.USER_ALREADY_EXIST);
        }

        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setNickname(registerDTO.getNickname());
        user.setScore(0);
        
        return userRepository.save(user);
    }

    public Map<String, Object> login(LoginDTO loginDTO) {
        User user = userRepository.findByUsername(loginDTO.getUsername())
                .orElseThrow(() -> new BusinessException(ResultCodeEnum.USER_NOT_EXIST));

        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException(ResultCodeEnum.PASSWORD_ERROR);
        }

        String token = jwtUtil.generateToken(user.getUsername());
        
        Map<String, Object> result = new HashMap<>();
        user.setPassword(null);
        result.put("user", user);
        result.put("token", token);
        
        return result;
    }
} 